import { MongoClient, ServerApiVersion } from "mongodb";

const { MONGODB_URL } = process.env;


// Create a MongoClient with a MongoClientOptions object to set the Stable API version
const client = new MongoClient(MONGODB_URL ?? '');

export async function run() {
  try {
    // Connect the client to the server	(optional starting in v4.7)
    await client.connect();
    // Send a ping to confirm a successful connection
    await client.db("admin").command({ ping: 1 });
    console.log(
      "Pinged your deployment. You successfully connected to MongoDB!"
    );
  } finally {
    // Ensures that the client will close when you finish/error
    await client.close();
  }
}

export function getDatabase() {
  if (!client.db("admin")) {
    throw new Error("Database not connected");
    //尝试重连
  }
  return client.db("admin");
}
